<template>
    <div class="fit row justify-center" style="overflow: auto; padding: 30px 0px">
        <div style="width: 1000px">
            <input type="file" id="fileInput" multiple />
            <VButton @click="uploadFiles">上传文件</VButton>
            <div style="font-size: 16px; margin-bottom: 10px">文件列表：</div>

            <div style="height: 600px; overflow: auto">
                <div class="column">
                    <div v-for="item in conf.list" class="row items-center file-item" style="padding: 10px; gap: 10px">
                        <div class="col" style="font-size: 12px">{{ item.name }}</div>
                        <div style="font-size: 12px">{{ new Date(item.createTime).Format() }}</div>
                        <VButton @click="downloadFile(item)">下载</VButton>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive } from 'vue'
import CFileUtil from '~/utils/CFileUtil'

const conf = reactive({
    list: [] as { createTime: number; name: string }[]
})

const rootUrl = 'http://192.168.31.59:3005'
const fileUrl = 'http://192.168.31.59'

http.setConfig({
    base: rootUrl
})

const uploadFiles = () => {
    const _fi = document.getElementById('fileInput') as any
    var files = _fi.files
    if (files.length == 0) return
    var formData = new FormData()

    for (var i = 0; i < files.length; i++) {
        formData.append('files[]', files[i])
    }

    var xhr = new XMLHttpRequest()
    xhr.open('POST', 'http://192.168.31.59:3005/saveFile', true)
    xhr.onload = function () {
        if (xhr.status === 200) {
            console.log(xhr)
            alert('文件上传成功！')
            getList()
        } else {
            alert('文件上传失败！')
        }
    }
    xhr.onerror = function () {
        alert('文件上传失败！')
    }
    xhr.send(formData)
}

const getList = async () => {
    const res = await http.post('/getConfig')
    conf.list = res.data.sort((a: any, b: any) => {
        return b.createTime - a.createTime
    })
}

const downloadFile = (item: any) => {
    CFileUtil.download(fileUrl + '/file/ac/' + item.name + '?time=' + Date.now(), item.name)
}

onMounted(() => {
    Timer.on(
        () => {
            getList()
        },
        3000,
        true
    )
})
</script>
<style lang="less" scoped>
.file-item {
    height: 60px;
    &:hover {
        background-color: #eee;
    }
}
</style>
~/utils/CFileUtil
